package com.global.college.security;

import android.text.TextUtils;
import android.util.Base64;

import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 自定义加解密算法
 */
public class CryptionUtil {

    /**
     * DES3加密
     * @param pwd
     * @return
     */
    public static String des3(String pwd){
        try {
            return Des3.encode(pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pwd;
    }

    /**
     * MD5加密密码
     *
     * @param pwd
     * @return
     */
    public static String md5(String pwd) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] strTemp = pwd.getBytes();
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获得签名
     * @param params
     * @return
     */
//    public static String getSignData(RequestParams params){
//        Map<String, String> map = new HashMap<String, String>();
//        for(String key : params.keySet()){
//            map.put(key, params.getParms().get(key));
//        }
//        return getSignData(map);
//    }

    /**
     * 参数排序签名
     *
     * @param params
     * @return
     * @throws Exception
     */
    public static String getSignData(Map<String, String> params){

        StringBuffer content = new StringBuffer();
        // 按照key做排序
        try{
            List<String> keys = new ArrayList<String>(params.keySet());
            Collections.sort(keys);

            for (int i = 0; i < keys.size(); i++) {

                String key = (String) keys.get(i);
                System.out.println(keys);
                if(params.get(key)!=null)
                {
                    String valueStr = params.get(key);
                    String valueStr1=Des3.encode(valueStr);
                    // 具体逻辑修改下面的路径进行拼接
                    content.append(valueStr1);
                }

            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return md5(content.toString() + Config.KEY);
    }

    /**
     * 参数排序签名
     *
     * @param params Map<String, String>
     * @return
     * @throws Exception
     */
    public static String getSignDataString(Map<String, String> params){

        StringBuffer content = new StringBuffer();
        // 按照key做排序
        try{
            List<String> keys = new ArrayList<String>(params.keySet());
            Collections.sort(keys);

            for (int i = 0; i < keys.size(); i++) {

                String key = (String) keys.get(i);
                System.out.println(keys);
                if(params.get(key)!=null)
                {
                    String valueStr = (String) params.get(key);
                    String valueStr1=Des3.encode(valueStr);
                    // 具体逻辑修改下面的路径进行拼接
                    content.append(valueStr1);
                }

            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return md5(content.toString()+Config.KEY);


    }


    /**
     * 获取密码强度
     * @param password
     * @return 1弱  2中  3强
     */
    public static String getPasswordSfae(String password){
        if(TextUtils.isEmpty(password)){
            return "1";
        }

        //数字，字母，特殊符号
        int hasNumber = 0;
        int hasZimu = 0;
        int hasOther = 0;

        //判断每一个字符
        char[] chars = password.toCharArray();
        for(char cha : chars){
            if(cha >= '0' && cha <= '9'){
                //0-9数字
                hasNumber = 1;
                continue;
            }

            //65-90, 97-122
            if((cha >= 'A' && cha <= 'Z') || (cha >= 'a' && cha <= 'z')){
                hasZimu = 1;
                continue;
            }else{

                //其他字符都算为特殊字符
                hasOther = 1;
            }
        }

        return String.valueOf(hasNumber + hasZimu + hasOther);
    }

    /**
     * 对支付返回数据解密
     * @param response
     * @return
     */
    public static JSONObject decodeBeforePayResult(JSONObject response){

        try {
            String mKey = response.optString("mkey");

            //坑爹的Des3,网络传输会将字符串变更
            mKey = mKey.replace("\\/", "/");
            mKey = mKey.replace("**", "hh");

            String responseDecode = Des3.decode(mKey);
            JSONObject newResponse = new JSONObject(responseDecode);

            return newResponse;

        }catch(Exception e){
            e.printStackTrace();

            return null;
        }

        //return response;
    }

    /**
     * 将对象转换成base64
     * @param object
     * @return
     */
    public static String objectToBase64(Object object){

        String base64 = "";
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(object);

            base64 = new String(Base64.encode(outputStream.toByteArray(), Base64.NO_WRAP));
            outputStream.close();
            objectOutputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return base64;
    }

    /**
     * 将base64转换成对象
     * @param base64
     * @return
     */
    public static Object base64ToObject(String base64){

        Object object = "";
        try {
            byte[] objBytes =  Base64.decode(base64.getBytes(), Base64.NO_WRAP);
            ByteArrayInputStream bais = new ByteArrayInputStream(objBytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            // 将byte数组转换成product对象
            object = ois.readObject();

            bais.close();
            ois.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return object;
    }
}
